package br.fbv.compreja.negocio.infra;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Context;
import br.fbv.compreja.activity.base.BuzzException;

public class LoginConttroler {

	private static final String PROP_FILE_USER_PROPERTIES = "user.properties";
	private static final String PROP_KEY_USER_PWD = "USER_PWD";
	private static final String PROP_KEY_USER_NAME = "USER_NAME";
	private static LoginConttroler instance;
	private String page;
	private String URL_WS = "http://www.ortomedicape.com.br/precobaixoja/login/check/";

	private LoginConttroler() {
		super();
	}

	public static LoginConttroler getIntance() {
		if (instance == null) {
			instance = new LoginConttroler();
		}
		return instance;
	}

	public void doLogin(Context context, String userName, String psw,
			boolean remember) {
		autenticarUsuario(userName, psw);
		try {
			Properties userProperties = new Properties();
			String savedUserName = "";
			String savedPsw = "";
			if (remember) {
				savedUserName = userName;
				savedPsw = psw;
			}

			userProperties.setProperty(PROP_KEY_USER_NAME, savedUserName);
			userProperties.setProperty(PROP_KEY_USER_PWD, savedPsw);

			FileOutputStream fos = context.openFileOutput(
					PROP_FILE_USER_PROPERTIES, Context.MODE_PRIVATE);
			userProperties.store(fos, null);
			fos.close();
		} catch (FileNotFoundException e) {
			throw new BuzzException("Arquivo não Encontrado.", e);
		} catch (IOException e) {
			throw new BuzzException("Problemas ao acessar o arquivo.", e);
		}
	}

	private boolean autenticarUsuario(String userName, String psw) {
		String url = URL_WS + userName + "/" + psw;
		boolean retorno = false;
		try {
			GetHttp http = new GetHttp(url);
			page = http.page;
			JSONObject object = (JSONObject) new JSONTokener(page).nextValue();
			JSONObject message = object.getJSONObject("retorno");

			if (message.getBoolean("error")) {
				String msg_error = "";
				if ("EMPTY".equals(message.getString("error_msg"))) {
					msg_error = "Falta de parametros";
				} else {
					msg_error = "Usuário não encontrado";
				}
				throw new BuzzException(msg_error);
			}
			retorno = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw new BuzzException(e.getMessage(), e);
		}

		return retorno;
	}

	public boolean logarAutomaticoAtivado(Context context) {
		try {
			Properties userProperties = new Properties();
			InputStream userConfig;
			userConfig = context.openFileInput(PROP_FILE_USER_PROPERTIES);
			userProperties.load(userConfig);
			String nome = userProperties.getProperty(PROP_KEY_USER_NAME);
			String psw = userProperties.getProperty(PROP_KEY_USER_PWD);
			userConfig.close();
			if (nome != null && nome.length() > 0 && psw != null
					&& psw.length() > 0) {
				return autenticarUsuario(nome, psw);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BuzzException e) {
			throw new BuzzException("Falha no Login automatico.");
		}
		return false;
	}
}
